﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Telerik.Web.UI;
using bts_webapp.Models;

namespace bts_webapp
{
    public class BasePage: System.Web.UI.Page
    {
        private BTSModelDataContext _dataContext;
        /// <summary>
        /// Get the current db context.
        /// </summary>
        protected BTSModelDataContext DbContext
        {
            get
            {
                if (_dataContext == null)
                {
                    _dataContext = new BTSModelDataContext();
                }
                return _dataContext;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (Common.CurrentUser == null)
            {
                Response.Redirect("~/Login.aspx", true);
            }

            if (this is UserChangePassword)
            {
                return;
            }

            const string radGridName = "RadGrid1";

            if (Common.CurrentUser.User_Role == 0)  //admin user, go throught normally
            {
                this.PopulateEditOnGrid(radGridName, true);
            }
            else if (Common.CurrentUser.User_Role == 1) //user 1
            {
                var permissions = Common.PermissionList;
                if (permissions == null)
                {
                    Response.Redirect("~/NotHavePermission.aspx", true);
                }
                var pageName = this.GetType().Name.ToLower();
                
                var perOnPage = permissions.FirstOrDefault(x => pageName.Contains(x.Page.ToLower()));
                if (perOnPage != null)
                {
                    this.PopulateEditOnGrid(radGridName, perOnPage.Action.ToLower() == "edit");
                }
                else 
                {
                    Response.Redirect("~/NotHavePermission.aspx", true);    
                }
            }
            else if (Common.CurrentUser.User_Role == 2)     //read only user.
            {
                //check permission on page UserManagement
                if (this is UserManagement) 
                {
                    Response.Redirect("~/NotHavePermission.aspx", true);
                }

                //find grids in this page
                PopulateEditOnGrid(radGridName, false);
            }

            this.ForceGridReadOnly(radGridName);
            SetupGridFilterOnKeyPress(radGridName);
        }

        private void SetupGridFilterOnKeyPress(string radGridName)
        {
            var ctrl = this.FindControlRecursive(radGridName);
            if (ctrl != null)
            { 
                var grid = (RadGrid)ctrl;
                
                if (grid.AllowFilteringByColumn)
                {
                    foreach (GridColumn col in grid.MasterTableView.Columns)
                        if (col.Visible)
                        {
                            col.AutoPostBackOnFilter = true;
                            grid.GroupingSettings.CaseSensitive = false;
                        }
                }
            }
        }

        private void ForceGridReadOnly(string radGridName)
        {
            var ctrl = this.FindControlRecursive(radGridName);
            if (ctrl != null)
            {
                var grid = (RadGrid)ctrl;
                if (this is Search || this is SendMessage || this is ViewMessage || this is UserPermission)
                {
                    grid.MasterTableView.CommandItemDisplay =  GridCommandItemDisplay.None;
                    //disable columns

                    GridColumn colEdit = grid.MasterTableView.Columns.Cast<GridColumn>().FirstOrDefault(c => c is GridEditCommandColumn && c.UniqueName == "ColumnEdit");
                    if (colEdit != null)
                        colEdit.Visible = false;
                    GridColumn colDelete = grid.MasterTableView.Columns.Cast<GridColumn>().FirstOrDefault(c => c is GridButtonColumn && c.UniqueName == "ColumnDelete");
                    if (colDelete != null)
                        colDelete.Visible = false;
                }
            }
        }

        private void PopulateEditOnGrid(string radGridName, bool isAllowEdit) 
        {
            var ctrl = this.FindControlRecursive(radGridName);

            if (ctrl != null)
            {
                var grid = (RadGrid)ctrl;
                
                grid.MasterTableView.CommandItemDisplay = isAllowEdit ? GridCommandItemDisplay.Top : GridCommandItemDisplay.None;
                //disable columns

                GridColumn colEdit = grid.MasterTableView.Columns.Cast<GridColumn>().FirstOrDefault(c => c is GridEditCommandColumn && c.UniqueName == "ColumnEdit");
                if (colEdit != null)
                    colEdit.Visible = isAllowEdit;
                GridColumn colDelete = grid.MasterTableView.Columns.Cast<GridColumn>().FirstOrDefault(c => c is GridButtonColumn && c.UniqueName == "ColumnDelete");
                if (colDelete != null)
                    colDelete.Visible = isAllowEdit;
            }
        }

        private Control FindControlRecursive(string id) {
            var stack = new Stack<Control>();
            for (int i = 0; i < this.Controls.Count; stack.Push(this.Controls[i++])) ;
            while (stack.Count > 0) {
                var ctrl = stack.Pop();
                if (ctrl.ID == id)
                    return ctrl;
                else
                    for (int i = 0; i < ctrl.Controls.Count; stack.Push(ctrl.Controls[i++])) ;
            }
            return null;
        }
    }
}